﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.SqlClient;

using PCC.Framework.Utils;

namespace TestApp
{
    class Class1
    {
        private static string _connStr;

        static void Main1(string[] args)
        {
            _connStr = "Data Source=.; Initial Catalog=scc; User ID= sa; Password=sa;";
            //SqlDependency.Start(_connStr);//传入连接字符串,启动基于数据库的监听
            //UpdateGrid();

            using (SqlConnection connection = new SqlConnection(_connStr))
            {
                //依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
                using (SqlCommand command = new SqlCommand("SELECT SID ,SNAME,SAGE FROM dbo.TA", connection))
                {
                    command.CommandType = CommandType.Text;
                    connection.Open();
                    SqlDataReader sdr = command.ExecuteReader();
                    DataTable dt = new DataTable();
                    dt.Load(sdr);
                    sdr.Close();
                    Console.WriteLine(JsonHelper.ToJson(dt));

                    DataSet ds = new DataSet();
                    ds.Tables.Add(dt);

                    dt = new DataTable();
                    dt.Columns.Add("a", typeof(string));
                    dt.Columns.Add("b", typeof(string));
                    dt.Rows.Add("acc", "bcc");

                    ds.Tables.Add(dt);

                    Console.WriteLine(JsonHelper.ToJson(ds));
                }
            }

            float s = ParseHelper.Parse<float>(null);

            Console.Read();
        }


        private static void UpdateGrid()
        {
            using (SqlConnection connection = new SqlConnection(_connStr))
            {
                //依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
                using (SqlCommand command = new SqlCommand( "SELECT SID ,SNAME,SAGE FROM dbo.TA", connection))
                {
                    command.CommandType = CommandType.Text;
                    connection.Open();
                    SqlDependency dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    SqlDataReader sdr = command.ExecuteReader();
                    Console.WriteLine();
                    while (sdr.Read())
                    {
                        Console.WriteLine("SID:{0}\tNAME:{1}\tAGE:{2}", sdr["SID"].ToString(), sdr["SNAME"].ToString(),sdr["SAGE"].ToString());
                    }
                    sdr.Close();
                }
            }
        }


        private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            UpdateGrid();
        }

    }
}
